import fetch from '../config/fetch'
import { Loading } from 'element-ui';
import * as config from '../config/const';

export const ADMIN_JSON='/adminjson';

export const userinfo = () => fetch(ADMIN_JSON+'/userinfo.json');
export const logout = () => fetch(ADMIN_JSON+'/logout.json');
export const lgabh = (param) => fetch(ADMIN_JSON+'/lgabh.json',param);


export const ajax = {
    data(){
      return {
        loadingTool:'',
        _imdoing:''
      }
    },
    methods: {
        async doajax(method,param,success,err){
          if (this._imdoing==method) {
            return;
          }
          this._imdoing=method;
          this.openLoading();
          this.ajax(await method(param),success,err);
          this.closeLoading();
          this._imdoing='';
        },
        ajax(res, success,err){
            if(res.success){
                success.call(this, res)
            }else{
              if(err!==undefined){
                    err.call(this, res);
                }else if(res.auth!==undefined){
                   var filter=config.AUTH_FILTER.admin;
                   this.$router.push(filter.loginUrl);
                 }else{
                    this.error(res.msg);
                }
            }

        },
      openLoading(){
        this.loadingTool=Loading.service({ fullscreen: true });
      },
      closeLoading(){
        this.loadingTool.close();
      },
      success(message){
        this.$message({
          message: message,
          type: 'success'
        });
      },
      error(message){
        this.$message.error(message);
      },
      warn(message){
        this.$message({
          message: message,
          type: 'warning'
        });
      }
    }
};
export const session={
  data(){
    return {}
  },
  mixins:[ajax],
  methods:{
    removeUser(){
      sessionStorage.removeItem(config.SESSION_KEY);
    },
    async getLoginUser(){
      //得到sessionStorage里的用户数据
      var user=sessionStorage.getItem(config.SESSION_KEY);
      if(user && user.indexOf('autostringify-') === 0 ){//有取到用户数据
        return JSON.parse(user.split('autostringify-')[1]);
      }else{//没取到直接用户数据，尝试去后台取
        //请求后端得到user
        await this.doajax(userinfo,{},(resp) => {
          sessionStorage.setItem(config.SESSION_KEY,'autostringify-'+JSON.stringify(resp.info));
          user=resp.info;
        });
        return user;
      }
    }
  }
};
